package com.ccrego.haiyi.app;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;

import com.ccrego.haiyi.account.UrlCenter;
import com.ccrego.haiyi.common.http.MyHttpRequest;
import com.ccrego.haiyi.common.web.FileUploadMessage;
import com.ccrego.haiyi.utils.ImageFileManager;
import com.pachong.android.framework.httprequest.HttpRequest;
import com.pachong.android.framework.httprequest.UrlParams;
import com.pachong.android.framework.httprequest.responsecallbacks.DataRequestListener;
import com.pachong.android.framework.picture.clipimage.PhotoActionHelper;
import com.pachong.android.framework.picture.picker.release.SelectAlbumActivity;
import com.pachong.android.frameworkbase.dialog.IOSAlertListFragment;
import com.pachong.android.frameworkbase.utils.BitmapUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.List;

import static android.app.Activity.RESULT_OK;
import static com.pachong.android.framework.picture.picker.Constants.Constants.IntentExtra.INTENT_SELECTED_PICTURE;

/**
 * Description:
 * Created by Andy Hong on 10/17/2017.
 */

public class UploadAvatarFragment extends Fragment {
    private ProgressDialog progressDialog;
    private boolean isAttach;
    private String picturePath;
    private String cropPath;
    private HttpRequest httpRequest;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        isAttach = true;
    }

    @Override
    public void onDetach() {
        super.onDetach();
        isAttach = false;
    }

    private void takePhoto() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File file = ImageFileManager.createImageFile(getContext());
        picturePath = file.getAbsolutePath();
        intent.putExtra(MediaStore.EXTRA_OUTPUT, ImageFileManager.createMediaUri(getContext(), file));
        startActivityForResult(intent, 1);
    }

    private void choosePhoto() {
        Intent intent = new Intent(getContext(), SelectAlbumActivity.class);
        intent.putExtra(SelectAlbumActivity.RELEASE_IMGS_NUM, 0);
        intent.putExtra(SelectAlbumActivity.INTENT_MAX_NUM, 1);
        startActivityForResult(intent, 2);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                cropPath = ImageFileManager.cropImageFile(getContext()).getAbsolutePath();
                clipImage(picturePath, cropPath);
            } else if (requestCode == 2) {
                List<String> urlList = data.getExtras().getStringArrayList(INTENT_SELECTED_PICTURE);
                if (urlList != null) {
                    picturePath = urlList.get(0);
                    cropPath = ImageFileManager.cropImageFile(getContext()).getAbsolutePath();
                    clipImage(picturePath, cropPath);
                }
            } else if (requestCode == 3) {
                setCropBitmapSize();
                updateAvatar(new File(cropPath));
            }

        }

    }

    private void updateAvatar(File file) {
        httpRequest = new MyHttpRequest(getContext());
        UrlParams urlParams = new UrlParams();
        urlParams.put("image", file);
        httpRequest.post(UrlCenter.UPLAOD_AVATAR, urlParams, new DataRequestListener<String>(String.class) {
            @Override
            public void onStart(Context context, String url) {
                super.onStart(context, url);
            }

            @Override
            public void onSuccess(String s) {
                super.onSuccess(s);
                FileUploadMessage message = new FileUploadMessage(FileUploadMessage.TYPE_PIC, FileUploadMessage.RESULT_SUCCESS, s);
                EventBus.getDefault().post(message);

            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                Toast.makeText(getContext().getApplicationContext(), t.getClass().getName() + strMsg, Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (isGranted(permissions, grantResults)) {
            if (requestCode == 1) {
                takePhoto();
            } else if (requestCode == 2) {
                choosePhoto();
            }
        } else {
            if (requestCode == 1) {
                Toast.makeText(getContext().getApplicationContext(), "权限不足，无法启动拍照", Toast.LENGTH_SHORT).show();
            } else if (requestCode == 2) {
                Toast.makeText(getContext().getApplicationContext(), "权限不足，无法选择图片", Toast.LENGTH_SHORT).show();
            }
        }
    }

    public boolean isGranted(String[] permissions, int[] grantResults) {
        if (permissions == null || permissions.length == 0) {
            return true;
        }
        for (int i = 0; i < grantResults.length; i++) {
            if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                return false;
            }
        }
        return true;
    }

    public void popupDialog() {
        if (isAttach) {
            final String[] actionArr = new String[]{"拍照", "从相册中选择"};
            final IOSAlertListFragment diaFrag = new IOSAlertListFragment();
            diaFrag.setActionList(new AdapterView.OnItemClickListener() {
                                      @Override
                                      public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                          switch (position) {
                                              case 0:
                                                  requestPermissions(new String[]{Manifest.permission.CAMERA,
                                                          Manifest.permission.READ_EXTERNAL_STORAGE,
                                                          Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
                                                  break;
                                              case 1:
                                                  requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                                                          Manifest.permission.WRITE_EXTERNAL_STORAGE}, 2);
                                                  break;
                                          }
                                          diaFrag.dismiss();
                                      }
                                  },
                    actionArr).show(getFragmentManager());
        }
    }

    private void setCropBitmapSize() {
        Bitmap userHeader = BitmapUtil.decodeBitmapFromFilePath(cropPath, 80, 80);
        BitmapUtil.saveBitmap(userHeader, cropPath, true);
    }

    private void clipImage(String url, String outputUrl) {
        int maxWidth = 0;
        int windowWidth = getActivity().getWindow().getWindowManager().getDefaultDisplay().getWidth();
        if (windowWidth <= 480) {
            maxWidth = 100;
        }
        PhotoActionHelper.clipImage(getActivity())
                .input(url)
                .output(outputUrl)
                .maxOutputWidth(maxWidth)
                .requestCode(3)
                .start(this);
    }
}
